package com.goldsprite.gameframeworks.ecs.system;

import com.goldsprite.gameframeworks.ecs.component.IComponent;
import com.goldsprite.gameframeworks.ecs.entity.*;
import com.goldsprite.gameframeworks.ecs.enums.*;
import java.util.*;

import com.goldsprite.gameframeworks.log.Debug;

@GameSystemInfo(type = GameSystemInfo.SystemType.BOTH)
public class SceneSystem extends BaseSystem {
	private final List<GObject> destroyGObjects = new ArrayList<>();
	private final List<IComponent> destroyComponents = new ArrayList<>();

	public void awakeScene() {
		for(GObject object : getInterestEntities()) {
			object.awake();
		}
	}

	@Override
	public void fixedUpdate(float fixedDelta){
		updateGObject(fixedDelta, true);
	}

	@Override
	public void update(float delta) {
		updateGObject(delta, false);
	}

	public void updateGObject(float delta, boolean isFixedUpdate) {
		List<GObject> gobjects = getInterestEntities();
		for (int i = gobjects.size() - 1; i >= 0; i--) {
			GObject obj = gobjects.get(i);
			if (obj.isDestroyed()) continue;

			if(isFixedUpdate)
				obj.fixedUpdate(delta);
			else
				obj.update(delta);
		}
	}

	public void executeDestroyTask() {
		//执行延迟销毁任务
		for (int i = destroyGObjects.size() - 1; i >= 0; i--) {
			GObject obj = destroyGObjects.get(i);
			if (obj != null) {
				obj.destroyImmediate();
				destroyGObjects.remove(obj);
				GameSystem.manageGObject(obj, ManageMode.REMOVE);
			}
		}
		for (int i = destroyComponents.size() - 1; i >= 0; i--) {
			IComponent comp = destroyComponents.get(i);
			if (comp != null) {
				comp.destroyImmediate();
				destroyComponents.remove(comp);
			}
		}
	}

	public void addDestroyGObject(GObject gobject) {
		destroyGObjects.add(gobject);
	}

	public void addDestroyComponent(IComponent component) {
		destroyComponents.add(component);
	}

//	/**
//	 * 清理当前场景
//	 */
//	private void clearScene() {
//		for (GObject obj : gobjects) {
//			if (obj != null) {
//				obj.destroyImmediate();
//			}
//		}
//		gobjects.clear();
//		destroyGObjects.clear();
//		destroyComponents.clear();
//	}

	public GObject findGObjectByName(String name) {
		for(GObject obj : getInterestEntities()) {
			if(obj.getName().equals(name)) return obj;
		}
		return null;
	}

	public GObject findGObjectByTag(String tag) {
		for(GObject obj : getInterestEntities()) {
			if(obj.getTag().equals(tag)) return obj;
		}
		return null;
	}

	/**
	 * 兼容旧版本的SceneData类
	 * @deprecated 建议使用新的SerializationSystem
	 */
	@Deprecated
	public static class SceneData {
		public final List<GObject> gobjects = new ArrayList<>();
		public final List<GObject> destroyGObjects = new ArrayList<>();
		public final List<IComponent> destroyComponents = new ArrayList<>();
	}
}
